package com.molyfun.parents.activity.course.downloadObserver;

import android.text.TextUtils;

import com.liulishuo.filedownloader.BaseDownloadTask;
import com.liulishuo.filedownloader.FileDownloadListener;
import com.molyfun.parents.MFPApplication;
import com.molyfun.parents.activity.course.bean.CourseMediaBean;
import com.molyfun.parents.activity.course.view.courseitem.CourseCellFactory;
import com.molyfun.parents.dao.entity.SingleDownloadTask;
import com.molyfun.parents.dao.gen.CourseDownloadTaskDao;
import com.molyfun.parents.dao.gen.DaoMaster;
import com.molyfun.parents.dao.gen.DaoSession;
import com.molyfun.parents.dao.gen.SingleDownloadTaskDao;
import com.molyfun.parents.impl.OnCourseDownloadTaskProgressUpdate;
import com.molyfun.parents.utils.Const;

import java.util.HashMap;
import java.util.List;

/**
 * Created by william(liuchao.hit@gmail.com).
 * Date:12/14/16.
 */
public class CourseDownloadContainer extends FileDownloadListener {

    private static final int COURSE_IMAGE_WEIGHT = 0x1 << 2;
    private static final int COURSE_MUSIC_WEIGHT = 0x1 << 3;
    private static final int COURSE_GAME_WEIGHT = 0x1 << 4;
    private static final int COURSE_VIDEO_WEIGHT = 0x1 << 5;

    private HashMap<String, Integer> mCoursesProgressMap = new HashMap<>();
    private HashMap<String, Integer> mCoursesWeightMap = new HashMap<>();

    private int mCurrentDownloadProgress = 0;

    private int totalDownloadProgress = 0;

    //双重验证
    private int mTotalFileCount = 0;

    private String mCourseDownloadId;

    private boolean isBegin = false;

    private CourseDownloadTaskDao courseDownloadTaskDao;
    private SingleDownloadTaskDao singleDownloadTaskDao;

    public CourseDownloadContainer(String courseDownloadId){
        mCourseDownloadId = courseDownloadId;
        DaoMaster.DevOpenHelper devOpenHelper = new DaoMaster.DevOpenHelper(MFPApplication.getInstance(), Const.DB_NAME, null);
        DaoMaster daoMaster = new DaoMaster(devOpenHelper.getWritableDatabase());
        DaoSession daoSession = daoMaster.newSession();
        courseDownloadTaskDao = daoSession.getCourseDownloadTaskDao();
        singleDownloadTaskDao = daoSession.getSingleDownloadTaskDao();
    }

    public void addCourse(CourseMediaBean courseMediaBean){
        System.out.println("CourseDownloadContainer--addCourse-->" + courseMediaBean.getType());
        switch (courseMediaBean.getType()){
            case CourseCellFactory.CourseType.COURSE_IMAGE:
                if(!TextUtils.isEmpty(courseMediaBean.getUrl())){
                    mCoursesWeightMap.put(courseMediaBean.getUrl(), COURSE_IMAGE_WEIGHT);
                    mCoursesProgressMap.put(courseMediaBean.getUrl(), 0);
                    totalDownloadProgress += COURSE_IMAGE_WEIGHT;
                    mTotalFileCount++;
                }
                break;
            case CourseCellFactory.CourseType.COURSE_MUSIC:
                if(!TextUtils.isEmpty(courseMediaBean.getUrl())){
                    mCoursesWeightMap.put(courseMediaBean.getUrl(), COURSE_MUSIC_WEIGHT);
                    mCoursesProgressMap.put(courseMediaBean.getUrl(), 0);
                    totalDownloadProgress += COURSE_MUSIC_WEIGHT;
                    mTotalFileCount++;
                }
                break;
            case CourseCellFactory.CourseType.COURSE_GAME:
                if(!TextUtils.isEmpty(courseMediaBean.getOfflineurl())){
                    mCoursesWeightMap.put(courseMediaBean.getOfflineurl(), COURSE_GAME_WEIGHT);
                    mCoursesProgressMap.put(courseMediaBean.getOfflineurl(), 0);
                    totalDownloadProgress += COURSE_GAME_WEIGHT;
                    mTotalFileCount++;
                }
                break;
            case CourseCellFactory.CourseType.COURSE_VIDEO:
                if(!TextUtils.isEmpty(courseMediaBean.getUrl())){
                    mCoursesWeightMap.put(courseMediaBean.getUrl(), COURSE_VIDEO_WEIGHT);
                    mCoursesProgressMap.put(courseMediaBean.getUrl(), 0);
                    totalDownloadProgress += COURSE_VIDEO_WEIGHT;
                    mTotalFileCount++;
                }
                break;
        }

    }

    public int getTotalFIleCounts(){
        return mTotalFileCount;
    }

    private OnCourseDownloadTaskProgressUpdate mOnCourseDownloadTaskProgressUpdate;

    public void setOnCourseDownloadTaskProgressUpdateListener(OnCourseDownloadTaskProgressUpdate onCourseDownloadTaskProgressUpdate){
        this.mOnCourseDownloadTaskProgressUpdate = onCourseDownloadTaskProgressUpdate;
    }

    @Override
    protected void pending(BaseDownloadTask task, int soFarBytes, int totalBytes) {
        System.out.println("pending--->" + task.getUrl());
        if(!isBegin){
            if (mOnCourseDownloadTaskProgressUpdate != null) {
                CourseDownloadProgressCenter.getInstance().setDownloadCourseStart(mCourseDownloadId);
                mOnCourseDownloadTaskProgressUpdate.onCourseDownloadStart(mCourseDownloadId);
            }
            isBegin = true;
        }
    }

    @Override
    protected void progress(BaseDownloadTask task, int soFarBytes, int totalBytes) {
        System.out.println("progress--->" + task.getUrl());
        if(!TextUtils.isEmpty(task.getUrl()) && (mCoursesProgressMap.get(task.getUrl()) < mCoursesWeightMap.get(task.getUrl()))){
            int currentPercent = (mCoursesWeightMap.get(task.getUrl()) * soFarBytes) / totalBytes;
            if(currentPercent >= mCoursesWeightMap.get(task.getUrl())){
                currentPercent = mCoursesWeightMap.get(task.getUrl());
            }
            if(currentPercent > mCoursesProgressMap.get(task.getUrl())){
                mCoursesProgressMap.put(task.getUrl(), currentPercent);
            }
            mCurrentDownloadProgress = 0;
            for(Integer progress : mCoursesProgressMap.values()){
                mCurrentDownloadProgress += progress;
            }
            if (mOnCourseDownloadTaskProgressUpdate != null) {
                if(mCurrentDownloadProgress >= totalDownloadProgress) {
                    CourseDownloadProgressCenter.getInstance().addFinishedDownloadCourse(mCourseDownloadId);
                    mOnCourseDownloadTaskProgressUpdate.onCourseDownloadFinish(mCourseDownloadId);
                }else{
                    mOnCourseDownloadTaskProgressUpdate.onCourseprogressUpdate(mCourseDownloadId, (mCurrentDownloadProgress * 100) / totalDownloadProgress);
                }
            }
        }
    }

    @Override
    protected void completed(BaseDownloadTask task) {
        System.out.println("completed--->" + task.getUrl());
        mCoursesProgressMap.put(task.getUrl(), mCoursesWeightMap.get(task.getUrl()));
        mCurrentDownloadProgress = 0;
        for(int progress : mCoursesProgressMap.values()){
            mCurrentDownloadProgress += progress;
        }
        if (mOnCourseDownloadTaskProgressUpdate != null) {
            if(mCurrentDownloadProgress >= totalDownloadProgress){
                CourseDownloadProgressCenter.getInstance().addFinishedDownloadCourse(mCourseDownloadId);
                mOnCourseDownloadTaskProgressUpdate.onCourseDownloadFinish(mCourseDownloadId);
            }else{
                mOnCourseDownloadTaskProgressUpdate.onCourseprogressUpdate(mCourseDownloadId, (mCurrentDownloadProgress * 100) / totalDownloadProgress);
            }
        }

    }

    @Override
    protected void paused(BaseDownloadTask task, int soFarBytes, int totalBytes) {
        System.out.println("paused--->" + task.getUrl());
    }

    @Override
    protected void error(BaseDownloadTask task, Throwable e) {
        System.out.println("error--->" + task.getUrl());
        if(mCoursesWeightMap.containsKey(task.getUrl())){
            mCoursesProgressMap.put(task.getUrl(), mCoursesWeightMap.get(task.getUrl()));
            mCurrentDownloadProgress = 0;
            for(Integer progress : mCoursesProgressMap.values()){
                mCurrentDownloadProgress += progress;
            }
            if(mOnCourseDownloadTaskProgressUpdate != null){
                if(mCurrentDownloadProgress >= totalDownloadProgress){
                    CourseDownloadProgressCenter.getInstance().addFinishedDownloadCourse(mCourseDownloadId);
                    mOnCourseDownloadTaskProgressUpdate.onCourseDownloadFinish(mCourseDownloadId);
                }else{
                    mOnCourseDownloadTaskProgressUpdate.onCourseprogressUpdate(mCourseDownloadId, (mCurrentDownloadProgress * 100) / totalDownloadProgress);
                }
            }
        }
        List<SingleDownloadTask> singleDownloadTasks = singleDownloadTaskDao.queryBuilder().where(SingleDownloadTaskDao.Properties.Url.eq(task.getUrl()), SingleDownloadTaskDao.Properties.DownloadKeyId.eq(mCourseDownloadId)).build().list();
        if(singleDownloadTasks != null && singleDownloadTasks.size() > 0){
            SingleDownloadTask singleDownloadTask = singleDownloadTasks.get(0);
            singleDownloadTask.setState(Const.DOWNLOAD_STATE_FAILED);
            singleDownloadTaskDao.update(singleDownloadTask);
        }
    }

    @Override
    protected void warn(BaseDownloadTask task) {
        System.out.println("warn--->" + task.getUrl());
        if(mCoursesWeightMap.containsKey(task.getUrl())){

            mCoursesProgressMap.put(task.getUrl(), mCoursesWeightMap.get(task.getUrl()));
            mCurrentDownloadProgress = 0;
            for(Integer progress : mCoursesProgressMap.values()){
                mCurrentDownloadProgress += progress;
            }
            if(mOnCourseDownloadTaskProgressUpdate != null){
                if(mCurrentDownloadProgress >= totalDownloadProgress) {
                    CourseDownloadProgressCenter.getInstance().addFinishedDownloadCourse(mCourseDownloadId);
                    mOnCourseDownloadTaskProgressUpdate.onCourseDownloadFinish(mCourseDownloadId);
                }else{
                    mOnCourseDownloadTaskProgressUpdate.onCourseprogressUpdate(mCourseDownloadId, (mCurrentDownloadProgress * 100) / totalDownloadProgress);
                }
            }
        }
    }


}
